var time = {};

/**
 * 格式化时间
 * 
 * @param {string} formatStr 
 * @param {string} time 毫秒
 * @returns {number[]}
 */
time.toArray = function (time) { };
(function () {
    let d = 0;
    let h = 0;
    let m = 0;
    let s = 0;
    let ms = 0;
    time.toArray = function (time) {
        ms = time % 1000;
        time = (time - ms) / 1000;
        d = ~~(time / 86400);
        time = time % 86400;
        h = ~~(time / 3600);
        time = time % 3600;
        m = ~~(time / 60);
        s = time % 60;
        return [d, h, m, s, ms];
    };
})();

/**
 * 格式化时间
 * 
 * @param {string} formatStr 
 * @param {string} time 毫秒
 * @returns 
 * 
 * @example
 * d => 天
 * h => 时
 * m => 分
 * s => 秒
 * ms => 毫秒
 * tool.formatTime("[%d : %h : %2m : %s : %3ms]", 86600);
 */
time.format = function (formatStr, time) { };
(function () {
    let ts = [];
    let str = '';
    const zeroTime = [0, 0, 0, 0, 0];

    const regd = /%d/g;
    const reg2d = /%2d/g;

    const regh = /%h/g;
    const reg2h = /%2h/g;

    const regm = /%m/g;
    const reg2m = /%2m/g;

    const regs = /%s/g;
    const reg2s = /%2s/g;

    const regms = /%ms/g;
    const reg3ms = /%3ms/g;

    time.format = function (formatStr, time) {
        if (time < 0) {
            time = 0;
        }

        ts = time ? this.toArray(time) : zeroTime;
        str = formatStr;

        if (formatStr.indexOf('%d') >= 0) {
            str = str.replace(regd, ts[0]);
        } else if (formatStr.indexOf('%2d') >= 0) {
            str = str.replace(reg2d, ts[0] > 9 ? ts[0] : ('0' + ts[0]));
        } else {
            ts[1] += ts[0] * 24;
        }
        if (formatStr.indexOf('%h') >= 0) {
            str = str.replace(regh, ts[1]);
        } else if (formatStr.indexOf('%2h') >= 0) {
            str = str.replace(reg2h, ts[1] > 9 ? ts[1] : ('0' + ts[1]));
        } else {
            ts[2] += ts[1] * 60;
        }
        if (formatStr.indexOf('ms') < 0) {
            if (formatStr.indexOf('%m') >= 0) {
                str = str.replace(regm, ts[2]);
            } else if (formatStr.indexOf('%2m') >= 0) {
                str = str.replace(reg2m, ts[2] > 9 ? ts[2] : ('0' + ts[2]));
            } else {
                ts[3] += ts[2] * 60;
            }
        }
        if (formatStr.indexOf('%s') >= 0) {
            str = str.replace(regs, ts[3]);
        } else if (formatStr.indexOf('%2s') >= 0) {
            str = str.replace(reg2s, ts[3] > 9 ? ts[3] : ('0' + ts[3]));
        } else {
            ts[4] += ts[3] * 1000;
        }
        if (formatStr.indexOf('%ms') >= 0) {
            str = str.replace(regms, ts[4]);
        } else if (formatStr.indexOf('%3ms') >= 0) {
            str = str.replace(reg3ms, ts[4] > 99 ? ts[4] : (ts[4] > 9 ? '0' + ts[4] : '00' + ts[4]));
        }
        return str;
    };
})();


module.exports = time;